import GameData from "./gamadata";

const {ccclass, property} = cc._decorator;

@ccclass
export default class RankItem extends cc.Component {

    @property(cc.Node)
    backSprite: cc.Node = null;
    @property(cc.Label)
    rankLabel: cc.Label = null;
    @property(cc.Sprite)
    avatarImgSprite: cc.Sprite = null;
    @property(cc.Label)
    nickLabel: cc.Label = null;
    @property(cc.Label)
    topScoreLabel: cc.Label = null;

    //冠军 
    @property(cc.Node)
    guanjun:cc.Node = null

    //亚军
    @property(cc.Node)
    yajun:cc.Node = null

    //季军
    @property(cc.Node)
    jijun:cc.Node = null

    //我的排行底
    @property(cc.Node)
    MypaihangDi:cc.Node = null

    //普通的排行底
    @property(cc.Node)
    putongpaihangdi:cc.Node = null



    start() {

      

    }

    init(rank, data) {
        this.MypaihangDi.active = false
        if(GameData.Instance.MyUser.nickName == data.nickname)
        {
            this.MypaihangDi.active = true
        }
        console.log('刷新Item',data)
        let avatarUrl = data.avatarUrl;
        // let nick = data.nickname.length <= 10 ? data.nickname : data.nickname.substr(0, 10) + "...";
        let nick = data.nickname;
        let grade = data.KVDataList.length != 0 ? data.KVDataList[0].value : 0;

        if (rank % 2 == 0) {
            this.putongpaihangdi.active = false
        }

        if (rank == 0) {
           this.guanjun.active = true
           this.rankLabel.node.active = false
        } else if (rank == 1) {
            this.yajun.active = true
            this.rankLabel.node.active = false
        } else if (rank == 2) {
           this.jijun.active = true
           this.rankLabel.node.active = false
        }
        this.rankLabel.string = (rank + 1).toString();
        this.createImage(avatarUrl);
        if(nick.length>7)
        {
            this.nickLabel.string = nick.substr(0,6);
        }
        else
        {
            this.nickLabel.string = nick;
        }
        this.topScoreLabel.string = grade.toString();
    }

    createImage(avatarUrl) {
        if (CC_WECHATGAME) {
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        this.avatarImgSprite.spriteFrame = new cc.SpriteFrame(texture);
                    } catch (e) {
                        this.avatarImgSprite.node.active = false;
                    }
                };
                image.src = avatarUrl;
            } catch (e) {
                this.avatarImgSprite.node.active = false;
            }
        } else {
            cc.loader.load({
                url: avatarUrl, type: 'jpg'
            }, (err, texture) => {
                this.avatarImgSprite.spriteFrame = new cc.SpriteFrame(texture);
            });
        }
    }
}
